/*
 * process.h
 *
 *  Created on: 2023年12月25日
 *      Author: Administrator
 */

#ifndef INC_PROCESS_H_
#define INC_PROCESS_H_

#ifndef _PROCESS_H
#define _PROCESS_H

#include <stdint.h>
#include <string.h>
#include <stdio.h>

#include "main.h"
#include "flash.h"
#include "stm32g4xx_hal_flash.h"

#define FLASH_APP     0x08010000
#define FLASH_DOWNLOAD     0x08020000
#define FLASH_USER_START_ADDR ((uint32_t)0x0803F000)//最后2页
#define FLASH_USER_END_ADDR ((uint32_t)0x0803FFFF)

#define BOOTLOADER_STATE 0
#define APPLICATION_STATE 1

#ifndef true
#define true 0x01
#endif
#ifndef false
#define false 0x00
#endif

typedef struct{
	uint8_t boot;
	uint8_t state;
	uint32_t size;
	uint32_t crc32;
}system_para_t;

//协议内容
#define SUITE_DEVTYPE 		0
#define SUITE_SRCDEVTYPE 	1
#define SUITE_SRCDEVNUM 	2
#define SUITE_DSTDEVTYPE 	3
#define SUITE_DSTDEVNUM 	4
#define SUITE_CMDTYPE 		5
#define SUITE_CHILDTYPE 	6
#define SUITE_DEVSTATE 		7
#define SUITE_DATALEN 		8
#define SUITE_MESSAGE 		12
#define SUITE_SZIE 				13

//命令
#define	IAP_VERSION		0
#define	IAP_START		1
#define	IAP_SENDDATA	2
#define	IAP_OVER		3
#define	IAPR_ERR		4
#define	IAP_LOG  		5
#define	IAP_BOOT 		6
#define	IAP_RESET 		7


//组件类型
#define  ASSEMBLY_ID   0
#define  ASSEMBLY_TYPE 1

//命令表构成
#define CMD_ID              0
#define CMD_DEVICE_TYPE     1
#define CMD_CMD_TYPE        2
#define CMD_CMD_CHILD_TYPE  3
#define CMD_LENGTH          4
#define CMD_MAX             5

#define CMD_HEARD 12
#define CMD_CACHE 4096+2

typedef struct{
	uint8_t m_DevType;
	uint8_t m_SrcDevType;
	uint8_t m_SrcDevNum;
	uint8_t m_DstDevType;
	uint8_t m_DstDevNum;
	uint8_t m_CmdType;
	uint8_t m_CmdChildType;
	uint8_t m_devState;
	uint32_t m_DataLen;
	uint8_t m_Message[CMD_CACHE];
} __attribute__ ((__packed__))  cmdStruct_t;

#define REPLY_CACHE 64
typedef struct{
	uint8_t m_DevType;
	uint8_t m_SrcDevType;
	uint8_t m_SrcDevNum;
	uint8_t m_DstDevType;
	uint8_t m_DstDevNum;
	uint8_t m_CmdType;
	uint8_t m_CmdChildType;
	uint8_t m_devState;
	uint32_t m_DataLen;
	uint8_t m_Message[REPLY_CACHE];
} __attribute__ ((__packed__))  replyStruct_t;


uint16_t calculateModbusCRC16(uint8_t *data, uint32_t length);

void process_iap_version(cmdStruct_t *suite);
void process_iap_start(cmdStruct_t *suite);
void process_iap_senddata(cmdStruct_t *suite);
void process_iap_over(cmdStruct_t *suite);
void process_iap_err(cmdStruct_t *suite);
void process_iap_log(cmdStruct_t *suite);
void process_iap_boot(cmdStruct_t *suite);
void process_iap_reset(cmdStruct_t *suite);
void iap_write_appbin(uint32_t appxaddr,uint8_t *appbuf,uint32_t appsize);
uint32_t iap_appbin_check(uint32_t appxaddr,uint32_t size);
void iap_load_app(__IO uint32_t Addr);

void process_decode(uint8_t *data,uint32_t len);
void process_encode(uint8_t *data,uint32_t len);

void process_jump(void);
#endif

void etwsSendto(uint8_t *data,uint32_t len);

#endif /* INC_PROCESS_H_ */
